package PCLiveWeb

import (
	"crypto/md5"
	"encoding/hex"
	"net/http"
	"reflect"
	"strconv"
	"strings"
	"time"

	"git.oschina.net/alwaysking/pclive/server/PCLiveServer"
)

type WebController struct {
}

type DaySummary struct {
	Morning   bool
	Afternoon bool
}

func JudgeTimeMoringOrAfternon(tstart time.Time, tend time.Time, tmpmap map[string]DaySummary) {
	// 开始时间
	startdate := tstart.Format("2006-01-02")
	if tstart.Hour() < 12 {
		TMP := tmpmap[startdate]
		TMP.Morning = true
		tmpmap[startdate] = TMP
	} else {
		TMP := tmpmap[startdate]
		TMP.Afternoon = true
		tmpmap[startdate] = TMP
	}

	// 结束时间
	enddate := tend.Format("2006-01-02")
	if tend.Hour() < 12 {
		TMP := tmpmap[enddate]
		TMP.Morning = true
		tmpmap[enddate] = TMP
	} else {
		TMP := tmpmap[enddate]
		TMP.Afternoon = true
		tmpmap[enddate] = TMP
	}

	// 如果结束时间和开始时间不是同一天
	if tend.Day() != tstart.Day() {
		TMP := tmpmap[startdate]
		TMP.Afternoon = true
		tmpmap[startdate] = TMP
	}
}

func (this *WebController) GetPCLiveListAction(w http.ResponseWriter, r *http.Request) {
	jsonpCallbackFunc := r.FormValue("jsoncallback")
	username := strings.ToUpper(r.FormValue("username"))
	onlinejsondata := ""
	offlinejsondata := ""
	var jsonpCallback string

	DataTableMachineList := make(map[string]bool)

	// 查询的在线表
	List, have := PCLiveServer.GetOnlineWithUser(username)
	if have {
		for index := range List {
			bef, _ := time.ParseDuration("-1m")
			nowtimestring := time.Now().Format("2006-01-02 15:04:05")
			nowtime, _ := time.Parse("2006-01-02 15:04:05", nowtimestring)
			oneMhbef := nowtime.Add(bef)
			cut := List[index].CurrentTime
			if cut.Before(oneMhbef) {
				// 过期了则更新online和data
				PCLiveServer.DeleteOnline(List[index].MAC)
				PCLiveServer.InsertData(List[index])
			} else {
				// 生成数据
				if len(onlinejsondata) != 0 {
					onlinejsondata += ","
				}
				starttime := List[index].StartTime.Format("2006-01-02 15:04:05")
				endtime := List[index].CurrentTime.Format("2006-01-02 15:04:05")
				onlinejsondata += "{\"hostname\":\"" + List[index].HostName + "\",\"mac\":\"" + List[index].MAC + "\",\"starttime\":\"" + starttime + "\",\"endtime\":\"" + endtime + "\"}"
				DataTableMachineList[List[index].MAC] = true
			}
		}
	}

	// 查询离线表
	tablename := username + "_DataTable"
	OffList, have2 := PCLiveServer.GetDataWithMachine(tablename)
	if have2 {
		for index := range OffList {
			if DataTableMachineList[OffList[index].MAC] == false {
				if len(offlinejsondata) != 0 {
					offlinejsondata += ","
				}

				starttime := OffList[index].StartTime.Format("2006-01-02 15:04:05")
				endtime := OffList[index].CurrentTime.Format("2006-01-02 15:04:05")
				offlinejsondata += "{\"hostname\":\"" + OffList[index].HostName + "\",\"mac\":\"" + OffList[index].MAC + "\",\"starttime\":\"" + starttime + "\",\"endtime\":\"" + endtime + "\"}"
			}
		}
	}

	if len(onlinejsondata) > 0 || len(offlinejsondata) > 0 {
		jsonpCallback = jsonpCallbackFunc + "({\"status\": \"success\",\"online\": [" + onlinejsondata + "], \"offline\": [" + offlinejsondata + "]})"
	} else {
		jsonpCallback = jsonpCallbackFunc + "({\"status\": \"No\"})"
	}

	w.Write([]byte(jsonpCallback))
}

func (this *WebController) GetPCLiveMonthAction(w http.ResponseWriter, r *http.Request) {
	jsonpCallbackFunc := r.FormValue("jsoncallback")
	username := strings.ToUpper(r.FormValue("username"))
	mac := r.FormValue("mac")
	year := r.FormValue("year")
	month := r.FormValue("month")
	jsondata := ""
	var jsonpCallback string

	tablename := username + "_DataTable"
	tmpmap := make(map[string]DaySummary)

	List, have := PCLiveServer.GetDataWithMonth(tablename, mac, year, month)
	if have {

		for index := range List {
			JudgeTimeMoringOrAfternon(List[index].StartTime, List[index].CurrentTime, tmpmap)
		}
	}

	// 检查当前在线的
	OnlineMachine, have2 := PCLiveServer.IsOnlineWithMac(mac)
	if have2 {
		JudgeTimeMoringOrAfternon(OnlineMachine.StartTime, OnlineMachine.CurrentTime, tmpmap)
	}

	for d := range tmpmap {
		// 生成数据
		if len(jsondata) != 0 {
			jsondata += ","
		}
		jsondata += "{\"date\":\"" + d + "\",\"m\":" + strconv.FormatBool(tmpmap[d].Morning) + ",\"a\":" + strconv.FormatBool(tmpmap[d].Afternoon) + "}"
	}

	jsonpCallback = jsonpCallbackFunc + "({\"status\": \"success\", \"mac\":\"" + mac + "\",\"daysummary\": [" + jsondata + "]})"

	w.Write([]byte(jsonpCallback))
}

func (this *WebController) GetPCLiveDayAction(w http.ResponseWriter, r *http.Request) {
	jsonpCallbackFunc := r.FormValue("jsoncallback")
	username := strings.ToUpper(r.FormValue("username"))
	mac := r.FormValue("mac")
	year := r.FormValue("year")
	month := r.FormValue("month")
	day := r.FormValue("day")
	jsondata := ""
	var jsonpCallback string

	tablename := username + "_DataTable"

	List, have := PCLiveServer.GetDataWithDay(tablename, mac, year, month, day)
	// 如果请求的就是今天
	nowtime := time.Now()
	if len(month) == 1 {
		month = "0" + month
	}
	requesttime, _ := time.Parse("2006-01-02", year+"-"+month+"-"+day)
	if nowtime.Day() == requesttime.Day() && nowtime.Month() == requesttime.Month() && nowtime.Year() == requesttime.Year() {
		OnlineMachine, have2 := PCLiveServer.IsOnlineWithMac(mac)
		if have2 {
			List = append(List, OnlineMachine)
			have = true
		}
	}

	if have {
		for index := range List {
			// 生成数据
			if len(jsondata) != 0 {
				jsondata += ","
			}

			var starttime string
			var shutdowntime string

			if List[index].StartTime.Day() < requesttime.Day() {
				starttime = "0:0:0"
			} else {
				starttime = List[index].StartTime.Format("15:04:05")
			}

			if List[index].CurrentTime.Day() > requesttime.Day() {
				shutdowntime = "24:0:0"
			} else {
				shutdowntime = List[index].CurrentTime.Format("15:04:05")
			}

			jsondata += "{\"starttime\":\"" + starttime + "\",\"shutdowmtime\":\"" + shutdowntime + "\"}"
		}
		// 检查当前在线的

		date := "" + year + "-" + month + "-" + day
		jsonpCallback = jsonpCallbackFunc + "({\"status\": \"success\", \"mac\":\"" + mac + "\",\"date\":\"" + date + "\",\"daydetail\": [" + jsondata + "]})"
	} else {
		jsonpCallback = jsonpCallbackFunc + "({\"status\": \"No\"})"
	}

	w.Write([]byte(jsonpCallback))
}

func (this *WebController) LoginAction(w http.ResponseWriter, r *http.Request) {
	var status string
	jsonpCallbackFunc := r.FormValue("jsoncallback")
	username := strings.ToUpper(r.FormValue("username"))
	password := r.FormValue("password")

	md5Ctx := md5.New()
	md5Ctx.Write([]byte(password))
	cipherStr := md5Ctx.Sum(nil)
	password = hex.EncodeToString(cipherStr)

	dbpassword, have := PCLiveServer.GetUser(username)
	if have {

		if password == dbpassword {
			status = "{\"status\": \"success\"}"

			// 存入cookie,使用cookie存储
			cookie := http.Cookie{Name: "PCLiveUserNmae", Value: username, Path: "/"}
			http.SetCookie(w, &cookie)
		} else {
			status = "{\"status\": \"密码不正确\"}"
		}

	} else {
		status = "{\"status\": \"不存在的用户名\"}"
	}

	jsonpCallback := jsonpCallbackFunc + "(" + status + ")"
	w.Write([]byte(jsonpCallback))
}

func PCLiveWebServer(w http.ResponseWriter, r *http.Request) {
	pathInfo := strings.Trim(r.URL.Path, "/")
	parts := strings.Split(pathInfo, "/")

	var action = ""
	if len(parts) > 1 {
		action = strings.Title(parts[1]) + "Action"
	}

	// 取得 WeatherController 接口的所有函数的反射值
	login := &WebController{}
	controller := reflect.ValueOf(login)
	// 取出我们需要的方法
	method := controller.MethodByName(action)
	// 处理异常
	if !method.IsValid() {
		method = controller.MethodByName(strings.Title("GetPCLiveList") + "Action")
	}

	// 包装参数
	requestValue := reflect.ValueOf(r)
	responseValue := reflect.ValueOf(w)

	// 调用函数
	method.Call([]reflect.Value{responseValue, requestValue})
}

func PcliveWebInit() {

}
